<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>设置库存预警</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label for="warningValue">库存预警值</label>
          <div class="warning-input-container">
            <input
              id="warningValue"
              v-model.number="warningValue"
              type="number"
              step="any"
              placeholder="请输入库存数量下限预警值"
              :class="{ 'error': showError && !isValidValue }"
            >
          </div>
          <div class="error-message" v-if="showError && !isValidValue">
            请输入大于0的数值
          </div>
          <div class="info-message">
            注意：您只能设置当前用户绑定的实验室对应的库存预警值
          </div>
        </div>
        
        <div v-if="currentConfig" class="current-config">
          <h4>当前预警设置</h4>
          <div class="config-info">
            <p><strong>实验室：</strong>{{ currentConfig.researchGroupName }}</p>
            <p><strong>预警值：</strong>{{ currentConfig.warningValue }}</p>
            <p><strong>更新时间：</strong>{{ formatDateTime(currentConfig.updateTime) }}</p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '确认' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import { ToastService } from '../../utils/toastService';

interface WarningConfig {
  researchGroupId: string;
  researchGroupName: string;
  warningValue: number;
  createTime: string;
  updateTime: string;
}

const props = defineProps<{
  show: boolean;
  labId: string;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'update-success'): void;
}>();

const warningValue = ref<number | null>(null);
const isSubmitting = ref(false);
const showError = ref(false);
const currentConfig = ref<WarningConfig | null>(null);

// 验证输入值是否有效
const isValidValue = computed(() => {
  return warningValue.value !== null && warningValue.value > 0;
});

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 获取当前预警配置
const fetchCurrentConfig = async () => {
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/research-group/warning/config?researchGroupId=${props.labId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    });

    const result = await response.json();
    
    if (result.code === '0' || result.code === 0) {
      currentConfig.value = result.data;
      // 如果有现有配置，设置为当前值
      if (result.data?.warningValue) {
        warningValue.value = result.data.warningValue;
      }
    }
  } catch (error) {
    console.error('获取预警配置失败:', error);
  }
};

// 提交表单
const handleSubmit = async () => {
  showError.value = true;
  
  if (!isValidValue.value) {
    return;
  }

  isSubmitting.value = true;
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/research-group/warning/config`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        researchGroupId: props.labId,
        warningValue: String(warningValue.value)
      })
    });

    const result = await response.json();
    
    if (result.code === '0' || result.code === 0) {
      emit('update-success');
      handleClose();
    } else {
      ToastService.error(`设置失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('设置预警值失败:', error);
    ToastService.error('设置预警值失败，请检查网络连接');
  } finally {
    isSubmitting.value = false;
  }
};

// 关闭模态框
const handleClose = () => {
  warningValue.value = null;
  showError.value = false;
  emit('close');
};

watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      fetchCurrentConfig();
    }
  },
  { immediate: true } // 立即执行一次，确保初始化时如果show为true也会获取配置
);
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.warning-input-container input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.warning-input-container input:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.warning-input-container input.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.info-message {
  color: #1890ff;
  font-size: 12px;
  margin-top: 8px;
  background-color: #e6f7ff;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.current-config {
  margin-top: 24px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.current-config h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #333;
}

.config-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}
</style>